package com.xx.controller;

import com.xx.entity.User;
import com.xx.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @author 许欣
 * 时间：2022/4/26 19:58
 * 描述：
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping(value = "/login")
    public String log(String name, String pwd, Model model){
        User loginUser=userService.getByAccount(name);
        if (loginUser==null){
            //不存在
            model.addAttribute("msg","账号不存在");
//            throw new RuntimeException("账号不存在");
        }else if (!loginUser.getPassword().equals(pwd)){
            //密码错误
            model.addAttribute("msg","密码错误");
           // throw new NullPointerException("密码错误");
        }else {
            model.addAttribute("msg","成功");
        }
        return "redirect:/user/list";
    }

    @RequestMapping(value = "/list")
    public String list(Model model){
        model.addAttribute("list",userService.getAll());
//        List<User>list=userService.getAll();
//        model.addAttribute(list);
        return "list";
    }
    //删除
//    @RequestMapping(value = "/del")
//    public String del(Integer id){
//        userService.delete(id);
//        return "redirect:/user/list";//进入controller
//    }
    //http://localhost:8081/frame_ch01_war_exploded/user/del/101
    @RequestMapping(value = "/del/{id}")
    public String del(@PathVariable Integer id){
        System.out.println(id);
        userService.delete(id);
        return "redirect:/user/list";//进入controller
    }
    @RequestMapping(value = "/toUpdate/{id}")
    public String toUpdate(@PathVariable Integer id,Model model){
        model.addAttribute("Auser",userService.getById(id));
        System.out.println(id);
        return "update";
    }
    @RequestMapping(value = "/update")
    public String update(@Valid User user, BindingResult result){
        userService.update(user);
        return "redirect:/user/list";
    }
//    @RequestMapping("/add")
//    public String add(@Valid User user, BindingResult result){
//        //数据校验
//        if (result.hasFieldErrors()){
//            return "add";
//        }
//        return "redirect:/user/list";
//    }
    @RequestMapping(value = "/toAdd")
    public String toAdd(){
        return "add";
    }
    @RequestMapping("/add")
    public String add( User user, BindingResult result){
        userService.add(user);
        return "redirect:/user/list";
    }

}
